package com.biao.mall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.biao.common.exception.NoStockException;
import com.biao.common.to.mq.OrderTo;
import com.biao.common.to.mq.StockDetailTo;
import com.biao.common.to.mq.StockLockedTo;
import com.biao.common.utils.PageUtils;
import com.biao.common.utils.Query;
import com.biao.common.utils.R;
import com.biao.mall.ware.dao.WareSkuDao;
import com.biao.mall.ware.entity.WareOrderTaskDetailEntity;
import com.biao.mall.ware.entity.WareOrderTaskEntity;
import com.biao.mall.ware.entity.WareSkuEntity;
import com.biao.mall.ware.feign.OrderFeignService;
import com.biao.mall.ware.feign.ProductFeignService;
import com.biao.mall.ware.service.WareOrderTaskDetailService;
import com.biao.mall.ware.service.WareOrderTaskService;
import com.biao.mall.ware.service.WareSkuService;
import com.biao.mall.ware.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    private WareSkuDao wareSkuDao;

    @Autowired
    private ProductFeignService productFeignService;


    @Autowired
    WareOrderTaskService orderService;

    @Autowired
    WareOrderTaskDetailService orderDetailService;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    OrderFeignService orderFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<WareSkuEntity> wrapper = new LambdaQueryWrapper<>();
        String skuId = (String) params.get("skuId");
        String wareId = (String) params.get("wareId");
        wrapper.eq(StringUtils.isNotBlank(skuId), WareSkuEntity::getSkuId, skuId);
        wrapper.eq(StringUtils.isNotBlank(wareId), WareSkuEntity::getWareId, wareId);
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //1、判断如果还没有这个库存记录新增
        List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (entities == null || entities.size() == 0) {
            WareSkuEntity skuEntity = new WareSkuEntity();
            skuEntity.setSkuId(skuId);
            skuEntity.setStock(skuNum);
            skuEntity.setWareId(wareId);
            skuEntity.setStockLocked(0);
            //TODO 远程查询sku的名字，如果失败，整个事务无需回滚
            //1、自己catch异常
            //TODO 还可以用什么办法让异常出现以后不回滚？高级
            try {
                R info = productFeignService.info(skuId);
                Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");

                if (info.getCode() == 0) {
                    skuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {

            }
            wareSkuDao.insert(skuEntity);
        } else {
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {

        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            Long count = baseMapper.getSkuStock(skuId);
            vo.setSkuId(skuId);
            if (count == null) {
                vo.setHasStock(false);
            } else {
                vo.setHasStock(count > 0);
            }


            return vo;
        }).collect(Collectors.toList());
        return collect;

    }

    /**
     * 锁定库存
     */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {
        /**
         *保存库存工作单详情,方便追溯
         */
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        orderService.save(taskEntity);
        //1、按照下单的收货地址，找到一个就近仓库，锁定库存
        //2、找到每个商品在哪个仓库都有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map((item) -> {//收集某个商品在那个仓库存在
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            //查询这个商品在哪个仓库有库存
            List<Long> wareIdList = wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIdList);
            return stock;
        }).collect(Collectors.toList());

        List<StockLockedTo> stockLockedTos = new ArrayList<>();
        for (SkuWareHasStock hasStock : collect) {
            boolean skuStocked = false;//标识,判断当前商品是否锁定成功
            List<Long> wareIds = hasStock.getWareId();
            Long skuId = hasStock.getSkuId();
            if (wareIds == null || wareIds.size() == 0) {
                //没有任何仓库有这个商品的库存
                throw new NoStockException(skuId);
            }
            for (Long wareId : wareIds) {
                Long count = wareSkuDao.lockSkuStock(skuId, wareId, hasStock.getNum());
                if (count == 1) {//数据库修改成功
                    skuStocked = true;
                    //告诉mq锁单成功
                    WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity(null, skuId, "", hasStock.getNum(), taskEntity.getId(), wareId, 1);
                    orderDetailService.save(detailEntity);
                    StockLockedTo to = new StockLockedTo();
                    StockDetailTo detailTo = new StockDetailTo();
                    to.setId(taskEntity.getId());
                    BeanUtils.copyProperties(detailEntity, detailTo);
                    //防止回滚之后找不到数据,所以保存完整库存单
                    to.setDetail(detailTo);
                    stockLockedTos.add(to);

                    break;
                }
            }
            if (!skuStocked) {
                //当前商品所有仓库都没有锁住
                throw new NoStockException(skuId);
            }

        }

        //到此,都是锁住的商品。调用此微服务的代码之前全部都是正确的,产生错误解锁订单只有：订单未支付,。调用此微服务的代码之后代码出错
        for (StockLockedTo to : stockLockedTos) {
            rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", to);
        }
        return true;
    }

    @Override
    public void unlockStock(StockLockedTo to) {
        log.info("----库存解锁ing  库存工作单Id={}",to.getId());
        StockDetailTo detail = to.getDetail();
        Long detailId = detail.getId();
        //解锁库存
        //1.查询关于这个订单的锁定库存信息
        WareOrderTaskDetailEntity orderTaskDetailEntity = orderDetailService.getById(detailId);
        Long id = to.getId();//库存工作单Id
        WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(id);
        String orderSn = taskEntity.getOrderSn();
        R r = orderFeignService.getOrderStatus(orderSn);
        if (!(r.getCode() == 0)) {
            throw new RuntimeException("远程服务失败");
        }
        OrderVo data = r.getData(new TypeReference<OrderVo>() {
        });
        //data == null 创建订单服务失败,锁定库存成功
        if (data == null || data.getStatus() == 4) {
            //没有这个订单 或者 有订单但订单状态是已取消,解锁库存
            //只有状态是1,才能解锁
            if (orderTaskDetailEntity.getLockStatus() == 1) {
                unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);
            }
        }
    }

    @Transactional
    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        //查询最新库存状态
        WareOrderTaskEntity task = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = task.getId();
        List<WareOrderTaskDetailEntity> list = orderDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", id)
                .eq("lock_status", 1));
        for (WareOrderTaskDetailEntity entity : list) {
            unLockStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum(), entity.getId());
        }
    }

    private void unLockStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        //库存解锁
        wareSkuDao.unlockStock(skuId, wareId, num);
        //更新库存工作单状态
        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
        entity.setId(taskDetailId);
        entity.setLockStatus(2);
        orderDetailService.updateById(entity);
    }
    //没有，库存锁定失败，库存回滚，这种情况无需解锁

}
